using System.Text;
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using Csla.Validation;
using BA.DAL;
using BA;

namespace BlazeApps.Library.Resources
{
    [Serializable()]
    public class ResourceDetail : Csla.BusinessBase<ResourceDetail>
    {
        private BlazeApps.Library.ConfigSettings Config = new BlazeApps.Library.ConfigSettings();
        private BA.DAL.DBUtility DAL = new BA.DAL.DBUtility();
        private Procedures Procs = new Procedures();

        #region Business Properties and Methods

        //declare members
        private Guid _resourceid = Guid.NewGuid();
        private string _resourcename = string.Empty;
        private int _resourcesize = 0;
        private string _resourcedesc = string.Empty;
        private string _contenttype = string.Empty;
        private byte[] _resource = new byte[0];
        private byte[] _thumbnail = new byte[0];
        private byte _deleteresource = 0;
        private SmartDate _createdate = new SmartDate(DateTime.Now);
        private Guid _resourcefolderid = Guid.Empty;
        private Guid _userid = Guid.Empty;
        private string _resourcetitle = string.Empty;
        private Guid _itemid = Guid.Empty;
        private Boolean _Private = false;

        [System.ComponentModel.DataObjectField(true, true)]
        public Guid resourceid
        {
            get
            {
                CanReadProperty("resourceid", true);
                return _resourceid;
            }
        }

        public string resourcename
        {
            get
            {
                CanReadProperty("resourcename", true);
                return _resourcename;
            }
            set
            {
                CanWriteProperty("resourcename", true);
                if (value == null)
                    value = string.Empty;
                if (!_resourcename.Equals(value))
                {
                    _resourcename = value;
                    PropertyHasChanged("resourcename");
                }
            }
        }

        public int resourcesize
        {
            get
            {
                CanReadProperty("resourcesize", true);
                return _resourcesize;
            }
            set
            {
                CanWriteProperty("resourcesize", true);
                if (!_resourcesize.Equals(value))
                {
                    _resourcesize = value;
                    PropertyHasChanged("resourcesize");
                }
            }
        }

        public string resourcedesc
        {
            get
            {
                CanReadProperty("resourcedesc", true);
                return _resourcedesc;
            }
            set
            {
                CanWriteProperty("resourcedesc", true);
                if (value == null)
                    value = string.Empty;
                if (!_resourcedesc.Equals(value))
                {
                    _resourcedesc = value;
                    PropertyHasChanged("resourcedesc");
                }
            }
        }

        public string contenttype
        {
            get
            {
                CanReadProperty("contenttype", true);
                return _contenttype;
            }
            set
            {
                CanWriteProperty("contenttype", true);
                if (value == null)
                    value = string.Empty;
                if (!_contenttype.Equals(value))
                {
                    _contenttype = value;
                    PropertyHasChanged("contenttype");
                }
            }
        }

        public byte[] resource
        {
            get
            {
                CanReadProperty("resource", true);
                return _resource;
            }
            set
            {
                CanWriteProperty("resource", true);
                if (!_resource.Equals(value))
                {
                    _resource = value;
                    PropertyHasChanged("resource");
                }
            }
        }

        public byte[] thumbnail
        {
            get
            {
                CanReadProperty("thumbnail", true);
                return _thumbnail;
            }
            set
            {
                CanWriteProperty("thumbnail", true);
                if (!_thumbnail.Equals(value))
                {
                    _thumbnail = value;
                    PropertyHasChanged("thumbnail");
                }
            }
        }

        public byte deleteresource
        {
            get
            {
                CanReadProperty("deleteresource", true);
                return _deleteresource;
            }
            set
            {
                CanWriteProperty("deleteresource", true);
                if (!_deleteresource.Equals(value))
                {
                    _deleteresource = value;
                    PropertyHasChanged("deleteresource");
                }
            }
        }

        public DateTime createdate
        {
            get
            {
                CanReadProperty("createdate", true);
                return _createdate.Date;
            }
        }

        public string createdateString
        {
            get
            {
                CanReadProperty("createdate", true);
                return _createdate.Text;
            }
            set
            {
                CanWriteProperty("createdate", true);
                if (value == null)
                    value = string.Empty;
                if (!_createdate.Equals(value))
                {
                    _createdate.Text = value;
                    PropertyHasChanged("createdate");
                }
            }
        }

        public Guid resourcefolderid
        {
            get
            {
                CanReadProperty("resourcefolderid", true);
                return _resourcefolderid;
            }
            set
            {
                CanWriteProperty("resourcefolderid", true);
                if (!_resourcefolderid.Equals(value))
                {
                    _resourcefolderid = value;
                    PropertyHasChanged("resourcefolderid");
                }
            }
        }

        public Guid Userid
        {
            get
            {
                CanReadProperty("Userid", true);
                return _userid;
            }
            set
            {
                CanWriteProperty("Userid", true);
                if (!_userid.Equals(value))
                {
                    _userid = value;
                    PropertyHasChanged("Userid");
                }
            }
        }

        public string resourcetitle
        {
            get
            {
                CanReadProperty("resourcetitle", true);
                return _resourcetitle;
            }
            set
            {
                CanWriteProperty("resourcetitle", true);
                if (value == null)
                    value = string.Empty;
                if (!_resourcetitle.Equals(value))
                {
                    _resourcetitle = value;
                    PropertyHasChanged("resourcetitle");
                }
            }
        }

        public Guid Itemid
        {
            get
            {
                CanReadProperty("Itemid", true);
                return _itemid;
            }
            set
            {
                CanWriteProperty("Itemid", true);
                if (!_itemid.Equals(value))
                {
                    _itemid = value;
                    PropertyHasChanged("Itemid");
                }
            }
        }

        public Boolean Private
        {
            get
            {
                return _Private;
            }
            set
            {
                CanWriteProperty("Private", true);
                if (!_Private.Equals(value))
                {
                    _Private = value;
                    PropertyHasChanged("Private");
                }
            }
        }

        protected override object GetIdValue()
        {
            return _resourceid;
        }

        #endregion //Business Properties and Methods

        #region Validation Rules
        private void AddCustomRules()
        {
            //add custom/non-generated rules here...
        }

        private void AddCommonRules()
        {
            //
            // resourcename
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "resourcename");
            //
            // contenttype
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "contenttype");
            //
            // createdate
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "createdateString");
        }

        protected override void AddBusinessRules()
        {
            AddCommonRules();
            AddCustomRules();
        }
        #endregion //Validation Rules

        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
            //TODO: Define authorization rules in ResourceDetail
            //AuthorizationRules.AllowRead("resourceid", "ResourceDetailReadGroup");
            //AuthorizationRules.AllowRead("resourcename", "ResourceDetailReadGroup");
            //AuthorizationRules.AllowRead("ize", "ResourceDetailReadGroup");
            //AuthorizationRules.AllowRead("resourcedesc", "ResourceDetailReadGroup");
            //AuthorizationRules.AllowRead("contenttype", "ResourceDetailReadGroup");
            //AuthorizationRules.AllowRead("resource", "ResourceDetailReadGroup");
            //AuthorizationRules.AllowRead("thumbnail", "ResourceDetailReadGroup");
            //AuthorizationRules.AllowRead("deleteresource", "ResourceDetailReadGroup");
            //AuthorizationRules.AllowRead("createdate", "ResourceDetailReadGroup");

            //AuthorizationRules.AllowWrite("resourcename", "ResourceDetailWriteGroup");
            //AuthorizationRules.AllowWrite("ize", "ResourceDetailWriteGroup");
            //AuthorizationRules.AllowWrite("resourcedesc", "ResourceDetailWriteGroup");
            //AuthorizationRules.AllowWrite("contenttype", "ResourceDetailWriteGroup");
            //AuthorizationRules.AllowWrite("resource", "ResourceDetailWriteGroup");
            //AuthorizationRules.AllowWrite("thumbnail", "ResourceDetailWriteGroup");
            //AuthorizationRules.AllowWrite("deleteresource", "ResourceDetailWriteGroup");
            //AuthorizationRules.AllowWrite("createdate", "ResourceDetailWriteGroup");
        }


        public static bool CanGetObject()
        {
            //TODO: Define CanGetObject permission in ResourceDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("ResourceDetailViewGroup"))
            //	return true;
            //return false;
        }

        public static bool CanAddObject()
        {
            //TODO: Define CanAddObject permission in ResourceDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("ResourceDetailAddGroup"))
            //	return true;
            //return false;
        }

        public static bool CanEditObject()
        {
            //TODO: Define CanEditObject permission in ResourceDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("ResourceDetailEditGroup"))
            //	return true;
            //return false;
        }

        public static bool CanDeleteObject()
        {
            //TODO: Define CanDeleteObject permission in ResourceDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("ResourceDetailDeleteGroup"))
            //	return true;
            //return false;
        }
        #endregion //Authorization Rules

        #region Factory Methods
        private ResourceDetail()
        { /* require use of factory method */
        }

        public static ResourceDetail NewResourceDetail()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a ResourceDetail");
            return DataPortal.Create<ResourceDetail>();
        }

        public static ResourceDetail GetResourceDetail(Guid resourceid)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("User not authorized to view a ResourceDetail");
            return DataPortal.Fetch<ResourceDetail>(new Criteria(resourceid));
        }

        public static void DeleteResourceDetail(Guid resourceid)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a ResourceDetail");
            DataPortal.Delete(new Criteria(resourceid));
        }

        public override ResourceDetail Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a ResourceDetail");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a ResourceDetail");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("User not authorized to update a ResourceDetail");

            return base.Save();
        }

        #endregion //Factory Methods

        #region Data Access

        #region Criteria

        [Serializable()]
        private class Criteria
        {
            public Guid resourceid;

            public Criteria(Guid resourceid)
            {
                this.resourceid = resourceid;
            }
        }

        #endregion //Criteria

        #region Data Access - Create
        [RunLocal]
        protected override void DataPortal_Create()
        {
            ValidationRules.CheckRules();
        }

        #endregion //Data Access - Create

        #region Data Access - Fetch
        private void DataPortal_Fetch(Criteria criteria)
        {
            ExecuteFetch(criteria);
        }

        private void ExecuteFetch(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            DAL.AddParameter("@resourceid", criteria.resourceid);

            using (SafeDataReader dr = new SafeDataReader(DAL.ExecuteReader(Procs.GetResourceByResourceID.ToString().Trim(), CommandType.Text, ConnectionState.Open)))
            {
                FetchObject(dr);
                ValidationRules.CheckRules();

                //load child object(s)
                FetchChildren(dr);
            }
        }

        private void FetchObject(SafeDataReader dr)
        {
            dr.Read();
            _resourceid = dr.GetGuid("resourceid");
            _resourcename = dr.GetString("resourcename");
            _resourcesize = dr.GetInt32("resourcesize");
            _resourcedesc = dr.GetString("resourcedesc");
            _contenttype = dr.GetString("contenttype");
            _resource = (byte[])dr["resource"];
            _thumbnail = (byte[])dr["thumbnail"];
            _deleteresource = dr.GetByte("archived");
            _createdate = dr.GetSmartDate("createdate", _createdate.EmptyIsMin);
            _userid = dr.GetGuid("userid");
            _resourcetitle = dr.GetString("resourcetitle");
        }

        private void FetchChildren(SafeDataReader dr)
        {
        }
        #endregion //Data Access - Fetch

        #region Data Access - Insert
        protected override void DataPortal_Insert()
        {
            ExecuteInsert();
        }

        private void ExecuteInsert()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddInsertParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.InsertResource.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddInsertParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@resourceid", _resourceid);
            DAL.AddParameter("@resourcename", _resourcename);
            DAL.AddParameter("@resourcesize", _resourcesize);

            if (_resourcedesc != string.Empty)
                DAL.AddParameter("@resourcedesc", _resourcedesc);
            else
                DAL.AddParameter("@resourcedesc", DBNull.Value);

            DAL.AddParameter("@contenttype", _contenttype);
            DAL.AddParameter("@resource", _resource);
            DAL.AddParameter("@thumbnail", _thumbnail);
            DAL.AddParameter("@nodeid", _resourcefolderid);

            if (_userid != Guid.Empty)
                DAL.AddParameter("@userid", _userid);
            else
                DAL.AddParameter("@userid", DBNull.Value);

            if (_resourcetitle != string.Empty)
                DAL.AddParameter("@resourcetitle", _resourcetitle);
            else
                DAL.AddParameter("@resourcetitle", DBNull.Value);

            DAL.AddParameter("@private", _Private);

        }
        #endregion //Data Access - Insert

        #region Data Access - Update
        protected override void DataPortal_Update()
        {
            if (base.IsDirty)
            {
                ExecuteUpdate();
            }
        }

        private void ExecuteUpdate()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddUpdateParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.UpdateResource.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddUpdateParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@resourceid", _resourceid);
            DAL.AddParameter("@resourcename", _resourcename);
            DAL.AddParameter("@resourcesize", _resourcesize);

            if (_resourcedesc != string.Empty)
                DAL.AddParameter("@resourcedesc", _resourcedesc);
            else
                DAL.AddParameter("@resourcedesc", DBNull.Value);

            DAL.AddParameter("@contenttype", _contenttype);
            DAL.AddParameter("@resource", _resource);
            DAL.AddParameter("@thumbnail", _thumbnail);

            if (_resourcetitle != string.Empty)
                DAL.AddParameter("@resourcetitle", _resourcetitle);
            else
                DAL.AddParameter("@resourcetitle", DBNull.Value);

            DAL.AddParameter("@private", _Private);
        }

        private void UpdateChildren(SqlConnection cn)
        {
        }
        #endregion //Data Access - Update

        #region Data Access - Delete
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new Criteria(_resourceid));
        }

        private void DataPortal_Delete(Criteria criteria)
        {
            ExecuteDelete(criteria);
        }

        private void ExecuteDelete(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddDeleteParameters(ref DAL, criteria);
            DAL.ExecuteNonQuery(Procs.DeleteResource.ToString().Trim(), CommandType.Text, ConnectionState.Open);

            Procs.PurgeItemsByItemID(criteria.resourceid);
        }

        private void AddDeleteParameters(ref BA.DAL.DBUtility DAL, Criteria criteria)
        {
            DAL.AddParameter("@resourceid", criteria.resourceid);
            DAL.AddParameter("@deleteresource", 1);
        }

        #endregion //Data Access - Delete

        #endregion //Data Access
    }
}
